#!/bin/bash

echo "🧪 Testing WSS Certificate Support"
echo "=================================="

# 检查是否存在测试证书
if [ ! -d "test-certs" ]; then
    echo "📁 Creating test certificates..."
    ./create-test-certs.sh
    echo ""
fi

# 检查证书文件
echo "📋 Certificate files status:"
for file in server-key.pem server-cert.pem ca-cert.pem; do
    if [ -f "test-certs/$file" ]; then
        echo "  ✅ test-certs/$file exists"
        # 显示证书信息
        if [[ "$file" == *cert.pem ]]; then
            echo "     Subject: $(openssl x509 -in test-certs/$file -noout -subject 2>/dev/null || echo 'Could not read')"
            echo "     Valid until: $(openssl x509 -in test-certs/$file -noout -enddate 2>/dev/null || echo 'Could not read')"
        fi
    else
        echo "  ❌ test-certs/$file missing"
    fi
done

echo ""
echo "🔧 Testing WebSocket servers:"

# 启动测试服务器（后台）
echo "  Starting test servers..."
node test-wss-server.js &
SERVER_PID=$!

# 等待服务器启动
sleep 2

# 测试普通WebSocket连接
echo "  Testing WS connection..."
if command -v wscat &> /dev/null; then
    echo "    Using wscat to test connections..."
    timeout 3s wscat -c ws://localhost:8080 --execute "test message" 2>/dev/null && echo "    ✅ WS connection successful" || echo "    ❌ WS connection failed"
    
    if [ -f "test-certs/server-cert.pem" ]; then
        echo "    Testing WSS connection..."
        timeout 3s wscat -c wss://localhost:8443 --no-check 2>/dev/null && echo "    ✅ WSS connection successful" || echo "    ❌ WSS connection failed"
    fi
else
    echo "    ⚠️  wscat not installed. Install with: npm install -g wscat"
    echo "    ✅ Servers appear to be running (check manually)"
fi

# 停止测试服务器
kill $SERVER_PID 2>/dev/null

echo ""
echo "📝 Manual Testing Instructions:"
echo "1. Start the test server: node test-wss-server.js"
echo "2. Open VS Code and run the Free WebSocket extension"
echo "3. Test connections:"
echo "   - WS: ws://localhost:8080 (no certificate needed)"
echo "   - WSS: wss://localhost:8443 (use test-certs/ca-cert.pem)"
echo ""
echo "🎯 Expected behavior:"
echo "  - WS connection should work without certificate"
echo "  - WSS connection should work with ca-cert.pem file"
echo "  - Error messages should appear for invalid certificates"
echo ""
echo "✨ Test complete!"
